import os.path
import time
from datetime import datetime, timedelta

import requests


class CiAPI:
    def __init__(self, log):
        self.log = log
        self.projectName = 'openharmony'
        self.branch = 'master'
        self.component = 'dayu200_split'
        self.manifest = 'default.xml'
        self.buildTarget = 'dayu200'
        self.downloadUrl = 'https://cidownload.openharmony.cn/'

    def request_daily_build(self):
        self.log.info('获取版本构建记录')
        today = datetime.today()
        yesterday = today - timedelta(1)

        url = 'https://ci.openharmony.cn/api/daily_build/build/list/component'
        data = {
            "projectName": self.projectName,
            "branch": self.branch,
            "pageNum": 1,
            "pageSize": 10,
            "deviceLevel": "",
            "component": self.component,
            "type": 1,
            "startTime": "{}000000".format(yesterday.strftime('%Y%m%d')),
            "endTime": "{}235959".format(today.strftime('%Y%m%d')),
            "sortType": "", "sortField": "",
            "hardwareBoard": "",
            "buildStatus": "",
            "buildFailReason": ""
        }
        for i in range(5):
            self.log.info('[Request]{}'.format(url))
            self.log.info('[请求参数]{}'.format(data))
            rsp = requests.post(url, json=data)
            if rsp.status_code != 200:
                time.sleep(60)
                continue
            rsp_data = rsp.json()
            if not rsp_data['data']:
                self.log.info('CI接口请求异常，error: {}，第{}次重试...'.format(rsp_data.get('error', ''), i))
                time.sleep(60)
                continue
            success_builds = []
            for build in rsp_data['data']['list']['dataList']:
                if build.get('buildSuccess') == 'true':
                    success_builds.append(build)
            return success_builds
        self.log.info('5次请求后仍然没有拿到版本构建数据，CI环境可能有异常')
        return []

    def request_trigger_events(self, start_time, end_time, page_num=1):
        url = 'https://ci.openharmony.cn/api/codecheckAccess/ci-portal/v1/events'
        params = {
            'pageNum': page_num,
            'pageSize': 50,
            'projectName': self.projectName,
            'branch': self.branch,
            'buildFailType': '',
            'startTime': start_time,
            'endTime': end_time,
            'triggerUser': '',
        }
        response = requests.get(url, params=params)
        return response.json().get('data', {})

    def request_tag_build(self, start_time, end_time, page_num):
        url = 'https://ci.openharmony.cn/api/codecheckAccess/tag/build'
        payload = {
            "projectName": self.projectName,
            "branch": self.branch,
            "manifestFile": self.manifest,
            "searchName": "",
            "startTime": start_time[:10],
            "endTime": end_time[:10],
            "pageNum": page_num,
            "pageSize": 50,
            "isDailyAnalysis": 0,
        }
        response = requests.post(url, json=payload)

        if response.status_code != 200:
            raise
        return response.json()

    def request_pr_pipeline(self, issue):
        url = 'https://ci.openharmony.cn/api/codecheckAccess/ci-portal/v1/pipelines'
        params = {
            'buildTarget': self.buildTarget,
            'causeUrl': issue
        }
        rsp_data = requests.get(url, params=params).json()
        comment_list = rsp_data['data']
        comment_list.sort(key=lambda c: c['timestamp'], reverse=True)
        for comment in comment_list:
            if comment['versionUrl']:
                return comment
        return {}

    def filter_tag(self, tag, start_time, end_time):
        if not (start_time <= tag['timestamp'] <= end_time) or not tag['issue']:
            return {}
        issue = tag.get('issue')
        if not issue:
            return {}
        comment = self.request_pr_pipeline(issue)
        if not comment:
            return {}
        return {
            'issue': issue,
            'pr': comment['pr'],  # 字符串，多笔pr之间英文逗号分隔
            'version_url': comment['versionUrl'],
            'build_time': datetime.strptime(comment['timestamp'], '%Y%m%d%H%M%S').strftime('%Y-%m-%d %H:%M:%S'),
            'merge_time': tag['timestamp']
        }

    def get_img_size(self, link):
        self.log.info('获取镜像大小')
        package_size = int(requests.head(link).headers['Content-Length'])
        return package_size

    def download_img(self, link, save_file):
        self.log.info('下载镜像')
        if os.path.exists(save_file):
            try:
                os.remove(save_file)
            except:
                pass
        t1 = time.time()
        rsp = requests.get(link, stream=True)
        with open(save_file, 'ab') as f:
            for chunk in rsp.iter_content(chunk_size=1024 * 1024):
                f.write(chunk)
        t2 = time.time()
        self.log.info('下载完成，耗时{}s'.format(int(t2 - t1)))
        return save_file
